package com.rub.android.ui.activity

import android.Manifest.permission
import android.location.*
import android.os.Bundle
import android.view.View
import android.widget.EditText
import androidx.annotation.RequiresPermission
import androidx.appcompat.app.AppCompatActivity
import com.rub.android.R
import com.rub.android.utils.logI
import java.util.*


class LocationActivity : AppCompatActivity() {
    var lm: LocationManager? = null
    var et: EditText? = null

    private var ll: LocationListener = object : LocationListener {
        override fun onLocationChanged(location: Location) {
            updateView(location)
        }

        override fun onProviderDisabled(provider: String) {
            updateView(null)
        }

        @RequiresPermission(anyOf = [permission.ACCESS_COARSE_LOCATION, permission.ACCESS_FINE_LOCATION])
        override fun onProviderEnabled(provider: String) {
            val l = lm!!.getLastKnownLocation(provider)
            updateView(l)
        }

        override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {
        }
    }

    @RequiresPermission(anyOf = [permission.ACCESS_COARSE_LOCATION, permission.ACCESS_FINE_LOCATION])
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_location)
        et = findViewById<View>(R.id.et) as EditText
        lm = getSystemService(LOCATION_SERVICE) as LocationManager
        var bestProvider = lm?.getBestProvider(criteria, true)
        if (bestProvider != null) {
            val l = lm?.getLastKnownLocation(bestProvider!!)
            updateView(l)
            lm?.requestLocationUpdates(bestProvider!!, 5000, 8f, ll)

        }

    }

    private val criteria: Criteria
        private get() {
            val c = Criteria()
            c.accuracy = Criteria.ACCURACY_COARSE
            c.isSpeedRequired = false
            c.isCostAllowed = false
            c.isBearingRequired = false
            c.isAltitudeRequired = false
            c.powerRequirement = Criteria.POWER_LOW
            return c
        }

    fun updateView(newLocation: Location?) {
        if (newLocation != null) {
            val latitude = newLocation.latitude.toString()
            val longitude = newLocation.longitude.toString()
            val Latitude = newLocation.latitude
            val Longitude = newLocation.longitude
            val city = getAddressbyGeoPoint(Latitude, Longitude)
            et!!.setText("您现在的位置是\n维度：")
            et!!.append(latitude)
            et!!.append("\n经度：")
            et!!.append(longitude)
            et!!.append("\n城市：")
            et!!.append(city)
            logI("dddd","城市:$city")
        } else {
            et!!.editableText.clear()
        }
    }
    //从地址Geopoint取得Address
    fun getAddressbyGeoPoint(Latitude: Double, Longitude: Double): String {
        var strReturn = ""
        try {
            /* 创建Geocoder对象，用于获得指定地点的地址 */
            val gc = Geocoder(this@LocationActivity, Locale.getDefault())

            /* 取出地理坐标经纬度*/

            /* 自经纬度取得地址（可能有多行）*/
            val lstAddress = gc.getFromLocation(Latitude, Longitude, 1)
            val sb = StringBuilder()

            /* 判断地址是否为多行 */if (lstAddress.size > 0) {
                val adsLocation = lstAddress[0]
                for (i in 0 until adsLocation.maxAddressLineIndex) {
                    sb.append(adsLocation.getAddressLine(i)).append("\n") //精确的地址和附近的代表建筑物
                }
                sb.append(adsLocation.locality).append("\n") //当前经纬度所在的城市（市）
                logI("adsLocation","locality=${adsLocation.locality},")
                logI("adsLocation","postalCode=${adsLocation.postalCode},")
                logI("adsLocation","countryName=${adsLocation.countryName},")
            }

            /* 将取得到的地址组合后放到stringbuilder对象中输出用 */
            strReturn = sb.toString()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return strReturn
    }
}